<?php

/**
 *  后台登录方法模型
 *  model
 */
namespace system\model;

use houdunwang\model\Model;

class Admin extends model
{
    //操作的数据表
    protected $table = "admin";

    //登录
    public function login()
    {
        //1.验证数据不能为空
        $res = Validate::make([
            //字段、验证规则、提示消息、验证条件,
            ['admin_username', 'isnull', '用户名不能为空', self::MUST_VALIDATE],
            ['admin_password', 'isnull', '密码不能为空', self::MUST_VALIDATE],
            ['code', 'isnull', '验证码不能为空', self::MUST_VALIDATE]
        ]);
        if ($res === false) {
            return ['valid' => 0, 'msg' => Validate::getError()];
            //print_r(Validate::getError());
        }
//        dd(Crypt::encrypt($_POST['admin_password']))->first();die;
        //2.比对用户名密码是否正确
        $userInfo = $this->where('admin_username', $_POST['admin_username'])->where('admin_password', Crypt::encrypt($_POST['admin_password']))->first();

        if (!$userInfo) {
            //用户名密码不对
            return ['valid' => 0, 'msg' => '用户名或者密码不正确'];
        }
        //3.比对验证码是否正确
        if(strtolower(Code::get())!=strtolower($_POST['code']))
        {
            return ['valid'=>0,'msg'=>'验证码不正确'];

        }

        //4.将当前登录用户信息存入session
        Session::set('admin.admin_id',$userInfo['admin_id']);
        Session::set('admin.admin_username',$userInfo['admin_username']);

        //7天免登陆
        if (isset($_POST['free'])) {
//            Cookie::set(Session::set('admin_id',$userInfo['admin_id']),Session::set('admin_username',$userInfo['admin_username']),time() + 3600 * 24 * 7, '/');
            Cookie::set(Session::get('admin.admin_id'),Session::get('admin.admin_username'),time() + 3600 * 24 * 7, '/','.hdphp.com');
        } else {
            Cookie::set(Session::get(), session_id(), 0, '/');

        }

//        dd(Session::all());die;
//        p(Session::get('admin.admin_username'));die;
        //5.返回成功
        return ['valid'=>1,'msg'=>'登录成功'];

    }

}